﻿using System;
using System.Collections;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Xml.Linq;
using E4D.AppFabric.Entities;
using MDCAdminTool.Configuration;

namespace MDCAdminTool
{
    public class Clusters : ObservableCollection<CacheCluster>
    {
        public string DistributedCacheConfigFile { get; set; }
        public ILogger Logger { get; set; }

        public Clusters()
        {
            
        }

		public void LoadFromConfiguration()
		{
			var config = CachingConfiguration.Read();
			if(config.Clusters.Count == 0)
			{
				Logger.Add("NOTE: Caching.config file is empty and does not point to any cache clusters.");
                Logger.Add("Using local cache cluster...");

				UseLocalCacheCluster();
				return;
			}

			foreach (var clusterElement in config.ClusterElements)
			{
				var cluster = new CacheCluster();
				cluster.Output = Logger;
				cluster.SetCacheCluster(clusterElement.Name, clusterElement.Provider, clusterElement.ConnectionString);
				cluster.Start();

				Add(cluster);
			}

		}

        public void SaveConfiguration()
        {
            // TODO: Considr refactoring using XML serialization.

            try
            {
                var doc = new XDocument(
                    new XElement("CachingConfig",
                                 new XElement("clusters",
                                              from c in this
                                              select new XElement("add",
                                                                  new XAttribute("name", c.Name),
                                                                  new XAttribute("connectionString", c.ConnectionString),
                                                                  new XAttribute("provider", c.Provider)))));

                doc.Save("caching.config");
            }
            catch (Exception ex)
            {
                Logger.Add(ex);
            }
        }

        private void UseLocalCacheCluster()
        {
            var cluster = new CacheCluster();
            try
            {
                //var DistributedCacheConfigFile = Settings.Default.DistributedCacheConfigFile;
                cluster.Output = Logger;
                cluster.InitCacheCluster( DistributedCacheConfigFile );
                
            }
            finally
            {
                Add( cluster );
            }
        }

    }
}
